// @dart=2.9
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_common/util/context_extension.dart';
import 'package:flutter_logan/flutter_logan.dart';
import 'package:flutter_screen_record/flutter_screen_record.dart';
import 'package:flutter_screen_recording_example/video_play_page.dart';
import 'package:flutter_screen_record/setting_background_widget.dart';
import 'dart:async';

import 'package:open_file/open_file.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:quiver/async.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  @override
  void initState() {
    super.initState();
    FlutterLogan.init('0123456789012345', '0123456789012345');
  }
  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Flutter Screen Recording'),
        ),
        body: Home(),
      ),
    );
  }
}

class Home extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return HomeState();
  }
}

class HomeState extends State  with ScreenCallback {

  bool recording = false;
  int _time = 0;

  requestPermissions() async {
    await [Permission.photos, Permission.microphone, Permission.storage]
        .request();
  }

  @override
  void onDuration(int duration, String formatText) {
    print("$duration -- $formatText");
  }

  @override
  void initState() {
    super.initState();
    requestPermissions();
    FlutterScreenRecord.bindScreenRecord(callBack: this);
  }

  @override
  void dispose() {
    super.dispose();
    FlutterScreenRecord.unbindScreenRecord();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Text('Time: $_time\n'),
        !recording
            ? Center(
                child: ElevatedButton(
                child: Text("Record Screen"),
                onPressed: () => startScreenRecord(false),
              ))
            : Container(),
        !recording
            ? Center(
                child: ElevatedButton(
                    child: Text("Record Screen & audio"),
                    onPressed: () => startScreenRecord(true)))
            : Center(
                child: ElevatedButton(
                    child: Text("Stop Record"),
                    onPressed: () => stopScreenRecord())),
        Expanded(
            child: SingleChildScrollView(
                child: SettingBackgroundWidget(
          appName: Platform.localeName,
          brand: 'xiaomi',
          appCode: 'pro',
        ))),
      ],
    );
  }

  startScreenRecord(bool audio) async {
    bool start = false;
    await Future.delayed(const Duration(milliseconds: 1000));
    Directory dir = await getExternalStorageDirectory();
    FlutterScreenRecord.startScreenRecord("${dir.path}/", 10*60, DateTime.now().millisecondsSinceEpoch, false, audio? 1 : 0, false, "");
  }

  stopScreenRecord() async {
    FlutterScreenRecord.stopScreenRecord();
    setState(() {
      recording = !recording;
    });
  }

  @override
  void onCallback(int code) {
    print(code);
  }

  @override
  void onStartRecording(p, i) {
    setState(() => recording = !recording);
  }

  @override
  void onStopRecord(Map result, id) {
    print("Opening video");
    print(result['file']);
    // OpenFile.open(result['file']);
    context.push(VideoPlayPage(file: File(result['file'])));
  }
}
